package com.itheima.pinkman.quartz;

import com.itheima.pinkman.mapper.RegistryMapper;
import com.itheima.pinkman.pojo.ServiceInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ClearJob {
    @Autowired
    RegistryMapper registryMapper;

    //每隔90秒清理一次
    @Scheduled(cron = "0 0/3 * * * ?")
    @Scheduled(cron = "30 1/3 * * * ?")
    public void clearService() {
        List<ServiceInfo> allService = registryMapper.findAllService();
        for (ServiceInfo serviceInfo : allService) {
            long updateTime = serviceInfo.getUpdateTime();
            long currentTime = System.currentTimeMillis();
            if (currentTime - updateTime > 120000) {
                registryMapper.delete(serviceInfo);
                if (allService.size() == 0) {
                    break;
                }
            }
        }
    }

    //心跳确认
    @Scheduled(cron = "0/30 * * * * ?")
    public void confirmRenew(){
        //根据更新时间判断,60s内没有续约标记为PAUSE暂停状态,再过30秒仍然没有续约就到了120秒的清理时间
        List<ServiceInfo> allService = registryMapper.findAllService();
        for (ServiceInfo serviceInfo : allService) {
            long updateTime = serviceInfo.getUpdateTime();
            long currentTime = System.currentTimeMillis();
            if (currentTime - updateTime > 60000) {
                serviceInfo.setServiceId("RENEW PAUSE");
                registryMapper.updateByRenew(serviceInfo);
                if (allService.size() == 0) {
                    break;
                }
            }
        }

    }

}
